var queues = require('mysql-queues');
const DEBUG = true;
var select = function(connection, callback) {
	var sql = 'select * from role_resource';
	connection.query(sql, function(err, rows) {
		if (err){
			console.log(err);
			console.log(err.stack);
		}
		callback(rows);
		connection.release();
	});
},
	add = function(connection, id, resource, callback) {
		queues(connection, DEBUG);
		var sql = 'insert into role_resource(roleId,resId,operation) values(?,?,?)';
		var trans = connection.startTransaction();
		for (var i = 0; i < resource.length; i++) {
			trans.query(sql, [id, resource[i].resId, resource[i].oper], function(err, rows) {
				if (err) {
					console.log(err);
					console.log(err.stack);
					trans.rollback();
				}
				callback(rows);
			});
		}
		trans.commit();
		trans.execute();
		console.log('execute add');
		connection.release();
	},
	delet = function(connection, id, callback) {
		queues(connection, DEBUG);
		var sql = 'delete from role_resource where id=?';
		var trans = connection.startTransaction();
		trans.query(sql, id, function(err, rows) {
			if (err) {
				console.log(err);
				console.log(err.stack);
				trans.rollback();
			} else {
				trans.commit(function(err, info) {
					console.log(info);
				});
			}
			console.log('rows', rows);
			callback(rows);
		});
		trans.execute();
		console.log('execute');
		connection.release();
	},
	update = function(connection, id, data, callback) {
		queues(connection, DEBUG);
		var delSql = 'delete from role_resource where roleId=?';
		var sql = 'insert into role_resource(roleId, resId, operation) values(?,?,?)';
		var trans = connection.startTransaction();
		trans.query(delSql, id, function(err, rows) {
			if (err) {
				console.log(err);
				console.log(err.stack);
				trans.rollback();
			} else {
				if (data.length == 0 || data.length == undefined) {
					trans.commit();
					callback("sueccess");
				} else {
					for (var i = 0; i < data.length; i++) {
						trans.query(sql, [id, data[i].resId, data[i].oper], function(err, rows) {
							if (err) {
								console.log(err);
								console.log(err.stack);
								trans.rollback();
							}
							console.log('rows', rows);
						});
					}
					trans.commit();
					callback("sueccess");
				}


			}
		});

		trans.execute();
		console.log('execute update');
		connection.release();
	},
	findById = function(connection, id, callback) {
		var sql = 'select * from role_resource where id=?';
		connection.query(sql, id, function(err, rows) {
			callback(rows);
			connection.release();
		});
	};

module.exports = {
	selectRoleResource: select,
	addRoleResource: add,
	deleteRoleResource: delet,
	updateRoleResource: update,
	findById: findById
};